<template>
  <div class="file-upload">
    <div
      class="upload-area"
      :class="{ 'is-dragover': isDargOver && darg, 'upload-area-drag': darg }"
      v-on="events"
    >
      <div>
        <slot name="loading" v-if="isLoading">
          <button>正在上传</button>
        </slot>
        <slot
          v-else-if="lastFile && lastFile.loaded"
          name="uploaded"
          :uploadFile="lastFile.data"
        >
          <button>点击上传</button></slot
        >
        <slot name="default" v-else>
          <button>点击上传</button>
        </slot>
      </div>
    </div>
    <input
      type="file"
      :multiple="multiple"
      :accept="accept"
      :with-credentials="withCredential"
      ref="fileInput"
      @change="hanldeFileChange"
      :style="{ display: 'none' }"
    />
    <ul class="upload-list" v-if="showUploadList">
      <li
        :class="`uploaded-file upload-${file.status}`"
        v-for="file in UploadList"
        :key="file.uid"
        @click="handlePreview(file)"
      >
        <span v-if="file.status === 'loading'" class="file-icon"
          ><LoadingOutlined
        /></span>
        <span v-else class="file-icon"><FileOutlined /></span>
        <span class="filename">{{ file.name }}</span>
        <span class="delete-icon" @click.stop="deleteFileItem(file.uid)"
          ><DeleteOutlined
        /></span>
      </li>
    </ul>
  </div>
</template>

<script lang="ts">
export default {
  name: 'FileUploader',
}
</script>
<script setup lang="ts">
import { reactive, ref, computed } from 'vue'
import {
  DeleteOutlined,
  LoadingOutlined,
  FileOutlined,
} from '@ant-design/icons-vue'
import axios from 'axios'
import { v4 } from 'uuid'
import { last } from 'lodash-es'
type UploadPropsType = {
  action: string
  beforeUpload?: CheckUpload
  onSuccess?: UploadSuccess
  onError?: (err: any, file: File, fileList: any) => void
  onPreview?: (file: File) => void
  onRemove?: (file: File, fileList: any) => void
  onProgress?: (evt: any, file: File, fileList: any, Progress: number) => void
  headers?: any
  fileName?: string
  multiple?: boolean
  accept?: string
  withCredential?: boolean
  darg?: boolean
  autoUpload?: boolean
  showUploadList?: boolean
}
const props = withDefaults(defineProps<UploadPropsType>(), {
  headers: {
    'Content-Type': 'multipart/form-data',
  },
  withCredential: false,
  darg: false,
  autoUpload: true,
  showUploadList: true,
})
interface FileUploader {
  uid: string
  size: number
  name: string
  status: UplaodStatus
  raw: File
  response?: any
}
type UplaodStatus = 'ready' | 'loading' | 'success' | 'error'
type CheckUpload = (file: File) => boolean | Promise<File>
type UploadSuccess = (response: any, file: File, fileList: any) => void

const fileInput = ref<HTMLInputElement | null>(null)
const UploadList = ref<FileUploader[]>([])
const isLoading = computed(() => {
  return UploadList.value.some((file) => file.status === 'loading')
})
const isDargOver = ref(false)
const lastFile = computed(() => {
  const Lfile = last(UploadList.value)
  if (Lfile) {
    return { loaded: Lfile.status === 'success', data: Lfile.response }
  } else {
    return false
  }
})
const handleClick = () => {
  if (fileInput.value) {
    fileInput.value.click()
  }
}
let events: { [key: string]: (e: any) => void } = {
  click: handleClick,
}
const fileToList = (file: File) => {
  const fileObj = reactive<FileUploader>({
    uid: v4(),
    size: file.size,
    name: file.name,
    status: 'ready',
    raw: file,
  })
  UploadList.value = [...UploadList.value, fileObj]
}
const hanldeFileChange = (e: Event) => {
  const target = e.target as HTMLInputElement
  const files = target.files
  if (files) {
    if (props.autoUpload) {
      if (props.beforeUpload) {
        const result = props.beforeUpload(files[0])
        if (result && result instanceof Promise) {
          result
            .then((processedFile) => {
              if (processedFile instanceof File) {
                uploadFile(processedFile)
              } else {
                throw new Error(
                  'beforeUpload Promise should return a File object'
                )
              }
            })
            .catch((e) => {
              console.error(e)
            })
        } else if (result !== false) {
          uploadFile(files[0])
        }
      } else {
        uploadFile(files[0])
      }
    } else {
      fileToList(files[0])
    }
  }
}
const deleteFileItem = (uid: string) => {
  const file: File = UploadList.value.find((file) => file.uid === uid)
  if (file) {
    UploadList.value = UploadList.value.filter((file) => file.uid !== uid)
    props.onRemove && props.onRemove(file, UploadList.value)
  }
}
const handlePreview = (file: File) => {
  if (props.onPreview) {
    props.onPreview(file)
  }
}

const uploadFile = (file: File) => {
  const formData = new FormData()
  formData.append(props.fileName ? props.fileName : 'file', file)

  const fileObj = reactive<FileUploader>({
    uid: v4(),
    size: file.size,
    name: file.name,
    status: 'loading',
    raw: file,
  })
  if (props.autoUpload) {
    UploadList.value.push(fileObj)
  } else {
    UploadList.value.find((item) => item.raw === file)!.status = 'loading'
  }

  axios
    .post(props.action, formData, {
      headers: {
        ...props.headers,
      },
      onUploadProgress: function (progressEvent) {
        // 计算已上传的百分比
        const percentCompleted = Math.round(
          (progressEvent.loaded * 100) / progressEvent.total
        )
        props.onProgress &&
          props.onProgress(
            progressEvent,
            file,
            UploadList.value,
            percentCompleted
          )
      },
    })
    .then((res) => {
      if (props.autoUpload) {
        fileObj.status = 'success'
        fileObj.response = res.data
      } else {
        UploadList.value.find((item) => item.raw === file)!.status = 'success'
        UploadList.value.find((item) => item.raw === file)!.response = res.data
      }

      props.onSuccess && props.onSuccess(res.data, file, UploadList.value)
    })
    .catch((err) => {
      if (props.autoUpload) {
        fileObj.status = 'error'
      } else {
        UploadList.value.find((item) => item.raw === file)!.status = 'error'
      }
      props.onError && props.onError(err, file, UploadList.value)
    })
    .finally(() => {
      if (fileInput.value) {
        fileInput.value.value = ''
      }
    })
}
const handleDarg = (e: DragEvent, over: boolean) => {
  e.preventDefault()
  isDargOver.value = over
}
const handleDorp = (e: DragEvent) => {
  e.preventDefault()
  isDargOver.value = false
  if (e.dataTransfer) {
    const file = e.dataTransfer.files[0]
    if (file) {
      uploadFile(file)
    }
  }
}
const uploadAllFileList = () => {
  if (props.autoUpload) return
  UploadList.value.forEach((file) => {
    if (file.status === 'ready') {
      uploadFile(file.raw)
    }
  })
}
defineExpose({
  submit: uploadAllFileList,
})
if (props.darg) {
  events = {
    ...events,
    dragover: (e: DragEvent) => {
      handleDarg(e, true)
    },
    dragleave: (e: DragEvent) => {
      handleDarg(e, false)
    },
    drop: handleDorp,
  }
}
</script>

<style scoped lang="scss">
.upload-area-drag {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 360px;
  height: 180px;
  padding: 20px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  background-color: #fafafa;
  transition: border-color 0.3s ease;
  &:hover {
    border-color: #40a9ff;
  }
  &.is-dragover {
    border-color: #40a9ff;
    background-color: #e6f7ff;
  }
}
.upload-img {
  width: 360px;
  min-height: 180px;
  padding: 20px;
  .a-img {
    width: 100%;
  }
}
.upload-list {
  margin: 0;
  padding: 0;
  list-style-type: none;
}
.upload-list li {
  transition: all 0.5s cubic-bezier(0.55, 0, 0.1, 1);
  font-size: 14px;
  line-height: 1.8;
  margin-top: 5px;
  box-sizing: border-box;
  border-radius: 4px;
  min-width: 200px;
  position: relative;
  &:first-child {
    margin-top: 10px;
  }
  .upload-list-thumbnail {
    vertical-align: middle;
    display: inline-block;
    width: 70px;
    height: 70px;
    position: relative;
    z-index: 1;
    background-color: #fff;
    object-fit: cover;
  }
  .file-icon {
    svg {
      margin-right: 5px;
      color: rgba(0, 0, 0, 0.45);
    }
  }
  .filename {
    margin-left: 5px;
    margin-right: 40px;
  }
  &.upload-error {
    color: #f5222d;
    svg {
      color: #f5222d;
    }
  }
  .file-status {
    display: block;
    position: absolute;
    right: 5px;
    top: 0;
    line-height: inherit;
  }
  .delete-icon {
    display: none;
    position: absolute;
    right: 7px;
    top: 0;
    line-height: inherit;
    cursor: pointer;
  }
  &:hover {
    background-color: #efefef;
    .file-status {
      display: none;
    }
    .delete-icon {
      display: block;
    }
  }
}
</style>
